package com.sfzd5.exam;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.sfzd5.exam.helplibrary.exam.PostAnserResult;

public class MainActivity extends AppCompatActivity {
    Button button;
    LinearLayout picsLinerLayout;
    TextView textView;
    PostAnserResult result;
    String picsJson;
    PApplication app;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        app = (PApplication)getApplication();
        button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new SubmitAsyncTask().execute(0);
            }
        });

        picsLinerLayout = findViewById(R.id.picsLinearLayout);
        textView = findViewById(R.id.textView);

        //识别过的结果，如果是选择题有一个txt，否则就一个图片
        result = app.result;

        if(result==null || result.tasksubmits==null || result.tasksubmits.size()==0){
            button.setEnabled(false);
            Toast.makeText(MainActivity.this, "识别失败", Toast.LENGTH_LONG).show();
        } else {
            picsJson = new Gson().toJson(result);
            LayoutInflater mInflater = LayoutInflater.from(this);
            for(Tasksubmit tasksubmit : result.tasksubmits){
                View convertView = mInflater.inflate(R.layout.submit_result, null);
                TextView tv_answer = convertView.findViewById(R.id.tv_answer);
                ImageView img_answer = convertView.findViewById(R.id.img_answer);

                tv_answer.setText("学生答案:" +tasksubmit.answer);
                Bitmap bitmap = MatBitmapConvert.base64ToBitmap(tasksubmit.answerBase64Pic);

                img_answer.setImageBitmap(bitmap);
                picsLinerLayout.addView(convertView);
            }
        }

    }


    class SubmitAsyncTask extends AsyncTask<Integer, Integer, Integer> {
        @Override
        protected void onPostExecute(Integer i) {
            super.onPostExecute(i);
            //MainActivity.this.finish();
            Toast.makeText(MainActivity.this, "上传完成", Toast.LENGTH_SHORT).show();
        }

        @Override
        protected Integer doInBackground(Integer... ints) {
            app.wsClient.send(picsJson);
            return 0;
        }
    }

}
